#include "yk_purchase_plan.h"
#include "ui_yk_purchase_plan.h"

#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QJsonDocument>
#include <QNetworkReply>
#include <QSqlError>
#include <QFile>
#include <QDir>

extern QList<QCameraInfo> cameraList;

Yk_purchase_plan::Yk_purchase_plan(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Yk_purchase_plan)
{
    ui->setupUi(this);

    initialFinished = false;

    //QApplication::setAttribute(Qt::AA_UseOpenGLES);

    //恢复当前窗口位置
    QSettings setIni("clin.ini", QSettings::IniFormat);
    QRect rct = setIni.value("windowState/yk_purchase_plan").toRect();
    this->setGeometry(rct);

    ui->de_plan->setDate(QDate::currentDate());
    ui->de_check->setDate(QDate::currentDate());
    ui->de_begin->setDate(QDate::currentDate());
    ui->de_end->setDate(QDate::currentDate());
    ui->de_begin_2->setDate(QDate::currentDate());
    ui->de_end_2->setDate(QDate::currentDate());

    ui->pb_pic_save->setEnabled(false);
    ui->pb_cap_remove->setEnabled(false);
    ui->pb_cap_take->setEnabled(false);
    ui->pb_cap_setup->setEnabled(false);
    ui->pb_set_pay_flag->setEnabled(false);

    remote_path = setIni.value("database/host_name").toString();

    if(remote_path.isEmpty())
    {
        remote_path = setIni.value("database/m_hostname").toString();
    }

    remote_path = "//" + remote_path + "/pics/pics_drug";

    //图片文件路径
    pic_path = pub::base_path + "/pics";
    QDir d = QDir(pic_path);

    if(!d.exists())
    {
        d.mkdir(pic_path);
    }
    else
    {
        //清空
        d.setNameFilters( QStringList("*.jpg") );
        QStringList files = d.entryList();  //read filenames

        for(int i = 0; i < files.size() ; i++)
        {
            QFile f(pic_path + "/" + files[i]);
            f.remove();
        }
    }

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    qrot = new QSqlQuery(pub::db_o);

    md_pics = new QSqlQueryModel(this);//图像
    md_search_list = new QSqlQueryModel(this);
    md_in_list = new QSqlQueryModel(this);
    md_search_pop = new QSqlQueryModel(this);
    md_check_list = new QSqlQueryModel(this);
    md_check_to_take_pic = new QSqlQueryModel(this);

    dlgGetItem = new Pub_pop_get_item();
    dlgDelay = new Pub_pop_delay();
//    cap_setup = new Ys_cap_setup();
    cap_setup = nullptr;

    //入出库临时表
    sq = "create temporary table if not exists tmp_pha_input_check (";
    sq += "atinc int auto_increment not null key, ";  //流水编码
    sq += "item_code VARCHAR(12) not null  , ";  //药品编码  unique
    sq += "item_name VARCHAR(100) not null,";          //品名
    sq += "fac_code varchar(10) not null, ";      //生产商代码
    sq += "fac_name varchar(64) not null, ";      //生产商名称
    sq += "specs varchar(50) not null,";               //规格
    sq += "approve_info VARCHAR(20) not null, "; //批准文号
    sq += "pack_qty varchar(10) not null , ";   //包装数量  decimal(10)
    sq += "pack_unit VARCHAR(12) not null , ";   //包装单位
    sq += "drug_type VARCHAR(5) not null , ";   //药品类别，中药，西药
    sq += "drug_quality VARCHAR(5) not null , ";   //药品类别，普药，特药
    sq += "retail_price varchar(10) not null , ";   //零售价格 decimal(12,2)
    sq += "purchase_price varchar(10) not null, ";   //采购价格 decimal(12,2)
    sq += "batch_no varchar(15), ";   //批号
    sq += "manu_date varchar(10), ";   //生产日期
    sq += "valid_date varchar(10), ";   //效期
    sq += "num varchar(10), ";   //出入数量
    sq += "invo_no varchar(25), ";   //发票号
    sq += "invo_date varchar(10), ";   //发票日期
    sq += "memo varchar(255), ";   //备注
    sq += "purchase_cost decimal(12,2) ,";   //购入金额
    sq += "retail_cost decimal(12,2) ,";   //零售金额
    sq += "min_unit varchar(10), ";   //最小单位
    sq += "group_code varchar(6),"; //组
    sq += "out_bill_code varchar(12),"; //出库单号
    sq += "out_serial_code varchar(6),"; //出库单序号
    sq += "out_list_code varchar(16),"; //出库单号
    sq += "med_list_codg varchar(45), ";   //医保码
    sq += "dose_model varchar(45), ";   //剂型
    sq += "check_result varchar(1) ";   //验收结论
    sq += ")";

    qDebug()<<"create temporary table :"<<sq<<"\n";
    if(!qrm->exec(sq))
    {
        QMessageBox::information(this,"note",qrm->lastError().text());
        return;
    }
    //增加临时表索引
    qrm->exec("alter table tmp_pha_input_check "
              " add unique index prim_key (item_code,batch_no)");

    qrm->exec("delete from tmp_pha_input_check");
//    showList();

    ui->tabWidget->setCurrentIndex(0);  //入库验收

    set_store_type();

//    if(ui->rb_pha->isEnabled())
//    {
//        ui->rb_pha->setChecked(true);
//    }
//    else if(ui->rb_mat->isEnabled())
//    {
//        ui->rb_mat->setChecked(true);
//    }

    state_pha = false;
    state_mat = false;
    has_edited = false;

    camera_initialized = false; //摄像头初始化标志
    pic_num = 0;
    camera = nullptr;
    viewfinder = nullptr;
    imageCapture = nullptr;
    view = new QGraphicsView(this);
    scene = new QGraphicsScene(this);
    pixmapItem = nullptr;
    view->setScene(scene);
    ui->hl_view->addWidget(view);

    //view->setFixedSize(800, 600);  // 固定显示区域大小

    connect(ui->tb_zoom_fit, &QToolButton::clicked, this, &Yk_purchase_plan::pic_fitToView); // 连接适应视图按钮
    connect(ui->tb_zoom_in, &QToolButton::clicked, this, &Yk_purchase_plan::pic_zoomIn);
    connect(ui->tb_zoom_out, &QToolButton::clicked, this, &Yk_purchase_plan::pic_zoomOut);


    initialFinished = true;
}

Yk_purchase_plan::~Yk_purchase_plan()
{
    dlgDelay->setText("正在释放摄像头设备。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    if(cap_setup != nullptr)
    {
        delete cap_setup;
        cap_setup = nullptr;
    }

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

    delete dlgGetItem;
    delete dlgDelay;

    delete ui;

}

void Yk_purchase_plan::on_pb_exit_clicked()
{
    if(has_edited)
    {
        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "当前验收类别包含未保存内容，是否放弃编辑？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
    }

    close();
}

void Yk_purchase_plan::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/yk_purchase_plan", QVariant(this->geometry()));

    emit destroyW( "yk_purchase_plan" );

}

void Yk_purchase_plan::set_store_type()
{

    if(has_edited)
    {
        if((state_mat && ui->rb_mat->isChecked()) ||
                (state_pha && ui->rb_pha->isChecked()))
        {
            //未变化
            return;
        }

        QMessageBox::StandardButton bt;
        bt = QMessageBox::question(this, "注意", "当前验收类别包含未保存内容，是否放弃编辑？");
        if(bt != QMessageBox::Yes)
        {
            if(state_mat)
            {
                ui->rb_mat->setChecked(true);
            }
            else if (state_pha)
            {
                ui->rb_pha->setChecked(true);
            }
            return;
        }
    }

    ui->rb_pha->setEnabled(false);
    ui->rb_mat->setEnabled(false);

    sq = " select role_dept from com_privileges "
         " WHERE role_dept in('物资','药库')  "
         " and type = 'role' and code = '" + pub::usr_code + "'";
    qDebug()<<"提取用户角色："<<sq<<"\n";

    qrm->exec(sq);
    while(qrm->next())
    {
        if(qrm->value(0).toString() == "药库")
        {
            ui->rb_pha->setEnabled(true);
        }

        if(qrm->value(0).toString() == "物资")
        {
            ui->rb_mat->setEnabled(true);
        }
    }

    ui->cbb_company->clear();
    ui->cbb_store_dept->clear();
    ui->cbb_company_2->clear();
    ui->cbb_store_dept_2->clear();

    if(ui->rb_pha->isEnabled() && ui->rb_mat->isEnabled())
    {
        //用户拥有多个权限，不做选择
    }
    else if(ui->rb_pha->isEnabled())
    {
        ui->rb_pha->setChecked(true);
    }
    else if(ui->rb_mat->isEnabled())
    {
        ui->rb_mat->setChecked(true);
    }

    if(ui->rb_pha->isEnabled() && ui->rb_pha->isChecked())
    {
        sq = "select FAC_NAME, FAC_CODE from PHA_COM_COMPANY where COMPANY_TYPE = '1' and VALID_FLAG = '1' order by FAC_NAME";
        qDebug()<<"提取药品采购供货公司："<<sq<<"\n";
        company_code = pub::fillCombo(ui->cbb_company, sq, -1, qrot);
        pub::fillCombo(ui->cbb_company_2, sq, -1, qrot);

        sq  = "select dept_name,dept_code from com_department where "
              " valid_state = '1' and dept_type in ('PI') order by dept_type,dept_name"; //'P'药房，'PI'药库
        qDebug()<<"提取药品入库目标："<<sq<<"\n";
        store_depts = pub::fillCombo(ui->cbb_store_dept, sq, -1, qrot);
        pub::fillCombo(ui->cbb_store_dept_2, sq, -1, qrot);

        state_pha = true;
        state_mat = false;
    }

    if(ui->rb_mat->isEnabled() && ui->rb_mat->isChecked())
    {
        sq = " select company_name, company_code from MAT_COM_COMPANY"
             " where COMPANY_TYPE = '1' and VALID_FLAG = '1' order by company_name";
        qDebug()<<"提取物资供货公司："<<sq<<"\n";
        company_code = pub::fillCombo(ui->cbb_company, sq, -1, qrot);
        pub::fillCombo(ui->cbb_company_2, sq, -1, qrot);

        sq  = "select dept_name,dept_code from com_department "
              " where valid_state = '1' and dept_type in ('L') order by dept_type,dept_name"; //'P'药房，'PI'药库
        qDebug()<<"提取物资入库目标："<<sq<<"\n";
        store_depts = pub::fillCombo(ui->cbb_store_dept, sq, -1, qrot);
        pub::fillCombo(ui->cbb_store_dept_2, sq, -1, qrot);

        state_pha = false;
        state_mat = true;
    }

    qrm->exec("delete from tmp_pha_input_check");

    //tmp_pha_input_check清空之后，showList 会置 has_edited 为 false
    showList();

    ui->tv_check_list->setModel(NULL);
    ui->lw_selected->clear();
    change_lock_status( true);
    ui->cbb_store_dept->setCurrentIndex(-1);
    ui->cbb_company->setCurrentIndex(-1);
}

void Yk_purchase_plan::on_pb_search_clicked()
{

    int pos;
    QString key = ui->le_key->text();
    QString company_code, dept_code;

    //检查当前工作库房
    if(ui->cbb_store_dept->currentText().isEmpty())
    {
        QMessageBox::warning(this, "注意", "未指定当前工作库房！" );
        return;
    }

    pos = pub::searchStr(store_depts, "^", ui->cbb_store_dept->currentText()) + 1;
    dept_code = pub::getStr(store_depts, "^", pos);


    //入库来源
    if(ui->cbb_company->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定供货单位！" );
            return;
        }
        pos = pub::searchStr(company_code, "^", ui->cbb_company->currentText()) + 1;
        company_code = pub::getStr(company_code, "^", pos);


        if(ui->rb_pha->isChecked())
        {
            sq = " select pha.TRADE_NAME 药品名称, pha.SPECS 规格, "
                     " f_c.fac_name 厂家, pha.APPROVE_INFO, "//0 - 3
                     " pha.PACK_QTY, pha.PACK_UNIT, pha.DRUG_TYPE, "
                     " pha.DRUG_QUALITY, pha.RETAIL_PRICE, pha.PURCHASE_PRICE,"//4 - 9
                     " pha.DRUG_CODE , pha.PRODUCER_CODE fac_code, "
                     " pha.min_unit, comp.med_list_codg, pha.dose_model_code";//10 - 14
                sq += " from pha_com_baseinfo pha "
                      " LEFT JOIN PHA_COM_COMPANY f_c ON f_c.FAC_CODE = pha.PRODUCER_CODE "
                      " LEFT JOIN fin_com_compare comp ON comp.FIXMEDINS_HILIST_ID = DRUG_CODE ";
                sq += " where pha.VALID_STATE = '1' ";
                sq += " and (pha.SPELL_CODE like '%" + key.toUpper() + "%' or pha.TRADE_NAME like '%" + key + "%' )";
                sq += " order by pha.TRADE_NAME";
        }
        else if(ui->rb_mat->isChecked())
        {
            sq = " select pha.item_name 物品名称, pha.SPECS 规格, "
                     " f_c.company_name 厂家, pha.APPROVE_INFO, "//0 - 3
                     " pha.PACK_QTY, pha.PACK_UNIT, pha.kind_code, "
                     " '0', pha.sale_PRICE, pha.in_PRICE,"//4 - 9  pha.DRUG_QUALITY
                     " pha.item_CODE , pha.factory_CODE , "
                     " pha.min_unit, comp.med_list_codg, '0'";//10 - 14  pha.dose_model_code
                sq += " from mat_com_baseinfo pha "
                      " LEFT JOIN mat_COM_COMPANY f_c ON f_c.company_CODE = pha.factory_CODE "
                      " LEFT JOIN fin_com_compare comp ON comp.FIXMEDINS_HILIST_ID = item_CODE ";
                sq += " where pha.VALID_flag = '1' ";
                sq += " and (pha.SPELL_CODE like '%" + key.toUpper() + "%' or pha.item_NAME like '%" + key + "%' )";
                sq += " order by pha.item_NAME";
        }
        else
        {
            QMessageBox::warning(this, "注意", "验收类别无效！");
            return ;
        }

    qDebug()<<"目录检索："<<sq<<"\n";
    md_search_list->setQuery(sq, pub::db_o);

    ui->tv_source->setModel(md_search_list);
    int width = ui->tv_source->width();

    pub::setColumnWidth(ui->tv_source, "0.3^0.2^0.4", width, 25);
    //"0.3^0.2^0.4^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0^0"

    //检索成功之后，禁止修改库存单位

    change_lock_status(false);

}

void Yk_purchase_plan::change_lock_status(bool status)
{
    ui->cbb_store_dept->setEnabled(status);
    ui->cbb_company->setEnabled(status);
    ui->cbb_store_dept->setEnabled(status);

    if(status)
    {
        ui->pb_unlock_status->setEnabled(false);
        //mdrs->setQuery(NULL);
    }
    else
    {
        ui->pb_unlock_status->setEnabled(true);
    }

}

void Yk_purchase_plan::on_le_key_returnPressed()
{
    on_pb_search_clicked();
}

void Yk_purchase_plan::on_tv_source_clicked(const QModelIndex &index)
{
    item_detail.clear();
    item_detail.insert("item_name", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("item_name_0", index.siblingAtColumn(0).data().toString());   //品名，用于比较
    item_detail.insert("specs", index.siblingAtColumn(1).data().toString());   //规格
    item_detail.insert("fac_name", index.siblingAtColumn(2).data().toString());   //生产商
    item_detail.insert("approve_info", index.siblingAtColumn(3).data().toString());   //批准文号, 项目维护的 drug_code

    item_detail.insert("pack_qty", index.siblingAtColumn(4).data().toString());   //包装数量
    item_detail.insert("pack_unit", index.siblingAtColumn(5).data().toString());   //包装单位
    item_detail.insert("drug_type", index.siblingAtColumn(6).data().toString());   //药品类别，中药，西药
    item_detail.insert("drug_quality", index.siblingAtColumn(7).data().toString());   //药品类别，普药，特药
    item_detail.insert("retail_price", QString::number(index.siblingAtColumn(8).data().toDouble(),'f',2));   //零售价格
    item_detail.insert("purchase_price", QString::number(index.siblingAtColumn(9).data().toDouble(),'f',2));   //采购价格（药品基本信息表）
    item_detail.insert("item_code", index.siblingAtColumn(10).data().toString());   //药品编码
    item_detail.insert("fac_code", index.siblingAtColumn(11).data().toString());   //生产商
    item_detail.insert("min_unit", index.siblingAtColumn(12).data().toString());  //最小单位
    item_detail.insert("med_list_codg", index.siblingAtColumn(13).data().toString());  //医保编码
    item_detail.insert("dose_model_code", index.siblingAtColumn(14).data().toString());  //剂型

    if(ui->rb_mat->isChecked())
    {
        item_detail.insert("dose_model", "-");  //剂型
    }
    else if(ui->rb_pha->isChecked())
    {
        sq = " select name from com_dictionary "
             " where type = 'DOSAGEFORM' and code = '" + item_detail["dose_model_code"] + "'";
        qDebug()<<"剂型代码转换名称："<<sq<<"\n";
        qro->exec(sq);
        qro->next();

        item_detail.insert("dose_model", qro->value(0).toString());  //剂型
    }
    else
    {
        QMessageBox::warning(this, "注意", "验收类别无效！");
        return ;
    }


qDebug()<<"item_detail"<<item_detail<<"\n";
    ui->le_approve_no->setText(item_detail["approve_info"]);
    ui->le_producer->setText(item_detail["fac_name"]);
    ui->le_pack_unit->setText(item_detail["pack_unit"]);
    ui->le_pack_qty->setText(item_detail["pack_qty"]);
    ui->le_dose_model->setText(item_detail["dose_model"]);
    ui->le_purch_price->setText(item_detail["purchase_price"]);
    ui->le_batch_no->setText("");
    ui->le_produced_date->setText("");
    ui->le_valid_date->setText("");
    ui->le_in_num->setText("");
    ui->le_memo->setText("");

    ui->le_batch_no->setFocus();

}

void Yk_purchase_plan::on_pb_add_clicked()
{
    if(!checkStatus("input_add_item"))
    {
        return;
    }

    //入库数据插入临时表
    sq = "replace into tmp_pha_input_check ("
         "item_code, item_name, fac_code, fac_name, specs, approve_info, ";  //药品编码,品名,生产商,规格,批准文号
    sq += "pack_qty, pack_unit, drug_type, ";   //包装数量,包装单位,药品中药西药类别
    sq += "drug_quality, retail_price, purchase_price,";   //药品普药特药类别，零售价格,采购价格
    sq += "med_list_codg,"; //医保码
    sq += "batch_no, manu_date, valid_date, num,";   //批号,生产日期,效期,数量
    sq += "memo, min_unit, purchase_cost,";   // 备注， 购入金额
    sq += "out_bill_code, out_list_code, out_serial_code, group_code,dose_model,check_result";//
    sq += ") values(";
    sq += "'" + item_detail["item_code"] + "',";//药品编码
    sq += "'" + item_detail["item_name"] + "',";//品名
    sq += "'" + item_detail["fac_code"] + "',";//生产商
    sq += "'" + item_detail["fac_name"] + "',";//生产商
    sq += "'" + item_detail["specs"] + "',";//规格
    sq += "'" + item_detail["approve_info"] + "',";//批准文号
    sq += "'" + item_detail["pack_qty"] + "',";//包装数量
    sq += "'" + item_detail["pack_unit"] + "',";//包装单位
    sq += "'" + item_detail["drug_type"] + "',";//药品类别，中药，西药
    sq += "'" + item_detail["drug_quality"] + "',";//药品类别，普药，特药
    sq += "'" + item_detail["retail_price"] + "',";//零售价格
    sq += "'" + ui->le_purch_price->text().trimmed() + "',";//采购价格
    sq += "'" + item_detail["med_list_codg"] + "',";//医保码
    sq += "'" + ui->le_batch_no->text().trimmed() + "',";//批号
    sq += "'" + ui->le_produced_date->text().trimmed() + "',";//生产日期
    sq += "'" + ui->le_valid_date->text().trimmed() + "',";//效期
    sq += "'" + QString::number(ui->le_in_num->text().toInt() *
                                item_detail["pack_qty"].toInt()) + "',";//数量
    //sq += "'" + ui->le_in_num->text() + "',";//数量
    sq += "'" + ui->le_memo->text().trimmed() + "',";//备注
    sq += "'" + item_detail["min_unit"] + "',";//备注
    sq += ui->le_purch_cost->text()+ ",";//购入金额
    sq += "'" + item_detail["out_bill_code"] + "',";//
    sq += "'" + item_detail["out_list_code"] + "',";//
    sq += "'" + item_detail["out_serial_code"] + "',";//
    sq += "'" + item_detail["group_code"] + "',";//
    sq += "'" + item_detail["dose_model"] + "',";//
    if(ui->cbb_result->currentText() == "合格")
    {
        sq += "'1'";//
    }
    else
    {
        sq += "'0'";//
    }

    sq += ")";

    qDebug()<<"insert data to temporary table : "<< sq;

    if(!qrm->exec(sq))
    {
        QMessageBox::warning(this, "注意", "插入临时表错误！\n" + qrm->lastError().text());
        return ;
    }

    showList();

}

void Yk_purchase_plan::showList()
{
    //计算合计金额
    sq = "select sum(purchase_cost) from tmp_pha_input_check ";
    qrm->exec(sq);
    qrm->next();
    double amount = qrm->value(0).toDouble();

    if(qFuzzyCompare(0, amount))
    {
        has_edited = false;
    }
    else
    {
        has_edited = true;
    }

    qDebug()<<"合计金额："<<ui->le_amount->text();
    sq = " select item_name 项目名称, SPECS 规格, fac_name 厂家, PACK_UNIT 包装单位, "
         " num / pack_qty 购入数量, purchase_cost 金额, item_code"
         " from tmp_pha_input_check order by atinc";

    qDebug()<<"待确认药品列表："<<sq;


        md_in_list->setQuery(sq, pub::db_m);
        ui->tv_in_list->setModel(md_in_list);
        int width = ui->tv_in_list->width();
        pub::setColumnWidth( ui->tv_in_list, "0.2^0.2^0.25^0.1^0.1^0.1^0^0^0^0^0^0^0", width, 20);
        ui->le_amount->setText(QString::number(amount, 'f', 2));
        ui->le_approve_no->setText("");
        ui->le_producer->setText("");

        ui->le_batch_no->setText("");
        ui->le_produced_date->setText("");
        ui->le_valid_date->setText("");
        ui->le_in_num->setText("");
        ui->le_purch_price->setText("");
        ui->le_memo->setText("");
        ui->le_pack_qty->setText("");
        ui->le_dose_model->setText("");


    ui->le_key->clear();
}

bool Yk_purchase_plan::checkStatus(QString mod)
{
    QDate dt_m, dt_v, dt;
    int testInt;
    double testDouble;
    bool convertValue;
    QString tmpStr;

    if(mod == "input_add_item")
    {
        //入库增加项目
        qDebug()<<"item_detail[drug_type] : "<<item_detail["drug_type"];

        if(item_detail["item_name_0"] != item_detail["item_name"] &&
                item_detail["specs_0"] != item_detail["specs"])
        {
            //检查录入状态是否有效
            QMessageBox::warning(this, "注意", "选定项目发生变更！");
            return false;
        }

        if(item_detail["drug_type"] != "C")
        {
            //非草药，检查批准文号
            if(ui->le_approve_no->text().isEmpty())
            {
                QMessageBox::warning(this, "注意", "未选定项目！");
                return false;
            }
        }

        if(ui->le_batch_no->text().trimmed().isEmpty()){
            QMessageBox::warning(this, "注意", "批号不可以空白！");
            return false;
        }

        dt_v = QDate::fromString(ui->le_valid_date->text(), "yyyy-MM-dd");
        if(!dt_v.isValid()){
            QMessageBox::warning(this, "注意", "效期录入无效！");
            return false;
        }

        dt_m = QDate::fromString(ui->le_produced_date->text(), "yyyy-MM-dd");
        if(!dt_m.isValid())
        {
            QMessageBox::warning(this, "注意", "生产日期录入无效！");
            return false;
        }

        testInt = ui->le_in_num->text().trimmed().toInt(&convertValue);
        if(testInt == 0)
        {
            QMessageBox::warning(this, "注意", "入库数量无效！");
            return false;
        }

        testDouble = ui->le_purch_price->text().trimmed().toDouble(&convertValue);
        if( qFuzzyCompare(testDouble, 0) || testDouble < 0)
        {
            QMessageBox::warning(this, "注意", "采购价格数值无效！");
            return false;
        }

        tmpStr = ui->le_purch_price->text().trimmed();
        tmpStr = tmpStr.mid(tmpStr.indexOf("."));
        if( tmpStr.length() - 1 > 3 )
        {
            QMessageBox::warning(this, "注意", "采购价格数值小数位数超限！");
            return false;
        }

        testInt = dt_m.daysTo(QDate::currentDate());
        if(testInt < 0 )
        {
            QMessageBox::warning(this, "注意", "生产日期不应该小于当前日期！");
            return false;
        }

        testInt = QDate::currentDate().daysTo(dt_v);
        if( testInt < 90 && ui->le_in_num->text().toInt() > 0)
        {
            //非退库，效期过短，不可以正数入库
            QMessageBox::warning(this, "注意", "效期小于三个月，不可以入库！");
            return false;
        }
    }
    else if(mod == "input_save_invoice")
    {
        //入库单据保存
        if(ui->cbb_store_dept->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择库存单位！");
            return false;
        }

        if(ui->cbb_company->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未选择入库供货商！");
            return false;
        }

        if(md_in_list->rowCount()<1)
        {
            QMessageBox::warning(this, "注意", "未录入项目数据！");
            return false;
        }
    }
    else
    {
        QMessageBox::warning(this, "注意", "校验模式选择无效！");
        return false;
    }
    return true;
}

void Yk_purchase_plan::on_pb_save_clicked()
{
    qDebug()<<"入库验收中间数据最终保存\n";
    if(!checkStatus("input_save_invoice"))
    {
        qDebug()<<"保存条件检查失败\n";
        return;
    }
    int pos;


    //检索科室代码
    pos = pub::searchStr(store_depts, "^", ui->cbb_store_dept->currentText()) + 1;
    QString dept_code = pub::getStr(store_depts, "^", pos);

    //检索代货商代码
    pos = pub::searchStr(company_code, "^", ui->cbb_company->currentText()) + 1;
    QString company = pub::getStr(company_code, "^", pos);
    QSqlRecord rcd;
    QMap<QString, QString> para;
    para["dept_code"] = dept_code;  //库存单位
    para["company"] = company; //供货公司
    para["state"] = "2"; //0 申请， 1审批， 2核准
    para["in_out"] = "in"; //入，出

    para["mode"] = "";

    pub::db_o.transaction();
    QString tmpSql;
    QSqlQuery tmpQr;

    sq = "select * from tmp_pha_input_check ";
    qrm->exec(sq);
    while(qrm->next())
    {

        para["list_code"] = "0";   //入库单据号
        para["serial_code"] = "0";   //

        //临时表当前行数据
        rcd = qrm->record();

        //生成 in_bill_code
        tmpSql = "SELECT SEQ_PHA_INPUT_CHECK.NEXTVAL FROM DUAL";
        tmpQr = pub::db_o.exec(tmpSql);
        tmpQr.next();
        para["check_list_no"] = tmpQr.value(0).toString();

        //保存 pha_com_input
        if(!ins_input(rcd, para))
        {
            pub::db_o.rollback();
            qDebug()<<"pha_com_input_check 保存失败，数据回滚\n";
            return;
        }

    }
    pub::db_o.commit();
    qrm->exec("delete from tmp_pha_input_check");
    showList();
    change_lock_status( true);
    ui->cbb_store_dept->setCurrentIndex(-1);
    ui->cbb_company->setCurrentIndex(-1);
    qDebug()<<"入库验收中间数据转储成功\n";
}

void Yk_purchase_plan::calc_amount()
{
    if(!initialFinished)
    {
        return;
    }

    int in_num;
    double price;

    bool oki = false;   //入库数量字串转换数值
    bool okd = false;   //价格字串转换数值

    in_num = ui->le_in_num->text().toInt(&oki);
    price =  ui->le_purch_price->text().toDouble(&okd);

    if(oki && okd)
    {
        ui->le_purch_cost->setText(QString::number(in_num * price, 'f', 2));
    }

}
void Yk_purchase_plan::on_le_purch_price_textChanged(const QString &arg1)
{
    calc_amount();

}

void Yk_purchase_plan::on_le_in_num_textChanged(const QString &arg1)
{
    calc_amount();
}

bool Yk_purchase_plan::ins_input(QSqlRecord rcd, QMap<QString, QString> para)
{

    sq = "insert into %1 ("
         "drug_dept_code,"//      VARCHAR2(4) not null,'库存科室 0-全部部门';
            "in_bill_code,"//        NUMBER(12),'入库单流水号'
            "serial_code,"//         NUMBER(4),'序号'
            "in_list_code,"//        VARCHAR2(20),'入库单据号'
            "drug_code,"//           VARCHAR2(12) not null,'药品编码'
            "trade_name,"//          VARCHAR2(50) not null,'药品商品名'
            "approve_no,"//          VARCHAR2(50),'批准文号'
            "specs,"//               VARCHAR2(32),'规格'
            "pack_unit,"//           VARCHAR2(16),'包装单位'
            "pack_qty,"//            NUMBER(4),'包装数'
            "min_unit,"//            VARCHAR2(16), '最小单位'
            "show_flag,"//           VARCHAR2(1),'显示的单位标记'
            "show_unit,"//           VARCHAR2(16),'显示的单位'
            "batch_no,"//            VARCHAR2(16),'批号'
            "valid_date,"//          DATE,'有效期'
            "producer_code,"//       VARCHAR2(10),'生产厂家'
            "company_code,"//        VARCHAR2(10),'供货单位代码'
            "retail_price,"//        NUMBER(12,4),'零售价'
            "purchase_price,"//      NUMBER(12,4),'购入价'
            "in_state,"//            VARCHAR2(1),'入库状态，0-验收完成，1-入库完成'
            "apply_num,"//           NUMBER(14,4),'申请入库量'
            "apply_opercode,"//      VARCHAR2(6),'申请入库操作员'
            "apply_date,"//          DATE,'申请入库日期'
            //"exam_num,"//            NUMBER(14,4),'审批数量'
            //"exam_opercode,"//       VARCHAR2(6),'审批人（药库发票入库人）'
            //"exam_date,"//           DATE,'审批日期（药库发票入库日期）'
            "pay_state,"//           VARCHAR2(1),'供货商结存付款状态 0 未付 1 未全付 2 付清'
            //"oper_code,"//           VARCHAR2(6),'操作员'
            //"oper_date,"//           DATE,'操作日期'
            "mark,"//                VARCHAR2(64),'备注'
            //"invoice_date,"//        DATE,'发票上的发票日期'
            //"in_date,"//             DATE,'入库时间，即实际入库发生时间'
            //"source_company_type,"// VARCHAR2(1) default '1','源科室（供货单位）类别  1 院内科室 2 供货单位 3 扩展'
            "manu_date,"//           DATE,'生产日期'
            "med_list_codg,"//       VARCHAR2(40), '医保代码'
            "input_check_no,"//      NUMBER(15) default 0,'入库验收流水号'
            "check_result,"//        VARCHAR2(1),'验收结果，1合格，0不合格
            "dose_model,"//          VARCHAR2(20)'剂型'
            "drug_type,"//
            "drug_quality,"//
            "valid_flag";//varchar(1)记录有效状态

    sq += " ) values (";

    sq += "'" + para["dept_code"] + "' ,";   //'库存科室 0-全部部门';
   sq += "0 ,";   //入库单流水号 para["bill_code"] +
   sq += para["serial_code"] + ",";   //'序号';
   sq += "'" + para["list_code"] + "' ,";   //'入库单据号';
   sq += "'" + rcd.value("item_code").toString() + "' ,";   //'药品编码';
   sq += "'" + rcd.value("item_name").toString() + "' ,";   //'药品商品名';
   sq += "'" + rcd.value("approve_info").toString() + "' ,";   //'批准文号';
   sq += "'" + rcd.value("specs").toString() + "' ,";   //'规格';
   sq += "'" + rcd.value("pack_unit").toString() + "' ,";   //'包装单位';
   sq += "'" + rcd.value("pack_qty").toString() + "' ,";   //'包装数';
   sq += "'" + rcd.value("min_unit").toString() + "' ,";   //'最小单位';
   sq += "'0' ,";   //'显示的单位标记';
   sq += "'' ,";   //'显示的单位';
   sq += "'" + rcd.value("batch_no").toString() + "' ,";   //'批号';
   sq += "to_date('" + rcd.value("valid_date").toString() + "','yyyy-mm-dd') ,";   //'有效期';
   sq += "'" + rcd.value("fac_code").toString() + "' ,";   //'生产厂家';
   sq += "'" + para["company"] + "' ,";   //'供货单位代码';
   sq += rcd.value("retail_price").toString() + " ,";   //'零售价';
   sq += rcd.value("purchase_price").toString() + " ,";   //'购入价';
   sq += "'0' ,";   //'入库状态，0-验收完成，1-入库完成';
   sq += rcd.value("num").toString() + " ,";   //'申请入库量';
   sq += "'" + pub::usr_code + "', SYSDATE, "; // -申请入库操作员 -申请入库日期
   //sq += "'' ,";   //'审批数量';
   //sq += "'' ,";   //'审批人（药库发票入库人）';
   //sq += "'' ,";   //'审批日期（药库发票入库日期）';
   sq += "'0' ,";   //'供货商结存付款状态 0 未付 1 未全付 2 付清';
   //sq += "'' ,";   //'操作员';
   //sq += "'' ,";   //'操作日期';
   sq += "'" + rcd.value("memo").toString() + "' ,";   //'备注';
   //sq += "'' ,";   //'发票上的发票日期';
   //sq += "'' ,";   //'入库时间，即实际入库发生时间';
   //sq += "'' ,";   //'源科室（供货单位）类别  1 院内科室 2 供货单位 3 扩展';
   sq += "to_date('" + rcd.value("manu_date").toString() + "','yyyy-mm-dd') ,";   //'生产日期';
   sq += "'" + rcd.value("med_list_codg").toString() + "' ,";   //'医保代码';
   sq += "'" + para["check_list_no"] + "' ,";   //'入库验收流水号';
   sq += "'" + rcd.value("check_result").toString() + "' ,";   //'验收结果，1合格，0不合格';
   sq += "'" + rcd.value("dose_model").toString() + "' ,";   //'剂型';
   sq += "'" + rcd.value("drug_type").toString() + "' ,";   //'剂型';
   sq += "'" + rcd.value("drug_quality").toString() + "' ,";   //'剂型';
   sq += "'1' ";   //'记录状态，1有效，0无效';

    sq += ")";

    if(ui->rb_mat->isChecked())
    {
        sq = sq.arg("MAT_COM_INPUT_CHECK");
    }
    else if(ui->rb_pha->isChecked())
    {
        sq = sq.arg("PHA_COM_INPUT_CHECK");
    }
    else
    {
        QMessageBox::warning(this, "注意", "验收类别无效！");
        return false;
    }

    qDebug()<<"插入入库验收记录 mat/pha _com_input_check : "<<sq<<"\n";

    pub::db_o.exec(sq);

    if(pub::db_o.lastError().isValid())
    {
        QMessageBox::warning(this, "注意", "插入 mat/pha _com_input_check 错误！\n" +
                             pub::db_o.lastError().text() + "\n");
        return false;
    }

    return true;
}

void Yk_purchase_plan::on_le_batch_no_returnPressed()
{
    if(ui->le_batch_no->text().trimmed().isEmpty())
    {
        return;
    }
    else
    {
        ui->le_produced_date->setFocus();
        ui->le_produced_date->selectAll();
    }
    ui->le_produced_date->setFocus();
}

void Yk_purchase_plan::on_le_produced_date_returnPressed()
{
    ui->le_valid_date->setFocus();
    ui->le_valid_date->selectAll();
}

void Yk_purchase_plan::on_le_valid_date_returnPressed()
{
    ui->le_purch_price->setFocus();
}

void Yk_purchase_plan::on_le_purch_price_returnPressed()
{
    ui->le_in_num->setFocus();
}

void Yk_purchase_plan::on_tv_in_list_clicked(const QModelIndex &index)
{
    QString item_code = index.siblingAtColumn(6).data().toString();
    item_detail.insert("item_name_0", index.siblingAtColumn(0).data().toString());   //品名
    item_detail.insert("specs_0", index.siblingAtColumn(1).data().toString());   //规格

    item_detail.insert("item_name_0" , index.siblingAtColumn(0).data().toString());
    sq = "select * from tmp_pha_input_check where item_code = '" + item_code + "'";
    qrm->exec(sq);
    qrm->next();

    ui->le_approve_no->setText(qrm->value("approve_info").toString());
    ui->le_producer->setText(qrm->value("fac_name").toString());
    //ui->leLsjg->setText(qrm->value("retail_price").toString());;
    ui->le_pack_qty->setText(qrm->value("pack_qty").toString());
    ui->le_pack_unit->setText(qrm->value("pack_unit").toString());
    //ui->le_purch_price->setText(qrm->value("purchase_price").toString());
    ui->le_batch_no->setText(qrm->value("batch_no").toString());
    ui->le_produced_date->setText(qrm->value("manu_date").toString());
    ui->le_valid_date->setText(qrm->value("valid_date").toString());
    ui->le_in_num->setText(QString::number(qrm->value("num").toInt()));// / qrm->value("pack_qty").toInt())
    ui->le_purch_price->setText(qrm->value("purchase_price").toString());
    //ui->leFph->setText(qrm->value("invo_no").toString());
    //ui->leFprq->setText(qrm->value("invo_date").toString());
}

void Yk_purchase_plan::on_pb_unlock_status_clicked()
{
    if(md_in_list->rowCount()>0)
    {
        QMessageBox::StandardButtons bt;
        bt = QMessageBox::question(this, "注意", "录入项目数据未保存，是否清除然后继续？");
        if(bt != QMessageBox::Yes)
        {
            return;
        }
        md_in_list->setQuery(NULL);
        qrm->exec("delete from tmp_pha_input_check");
    }
    change_lock_status(true);
}

void Yk_purchase_plan::on_pb_search_2_clicked()
{
    QString key = ui->le_key_browse->text().trimmed();

    if(key.isEmpty())
    {
        QMessageBox::information(this, "注意", "请录入检索关键字！");
        ui->le_key_browse->setFocus();
        return;
    }

    mpRecipeItemInfo.clear();

    if(ui->rb_pha->isChecked())
    {
        sq = "select BASE.trade_name 药品名称, BASE.specs 规格, BASE.drug_code, "//0-2
                "BASE.pack_qty, BASE.drug_type,BASE.retail_price, "//3-5
                " BASE.pack_unit, BASE.drug_quality , "//6-7
                "BASE.DOSE_MODEL_CODE,BASE.SELF_Flag,BASE.FEE_CODE,"//8-10
                "BASE.CLASS_CODE,BASE.BASE_DOSE,"//11-12
                " COMP.FAC_NAME 生产厂家, base.dose_unit " //13-14
                " from pha_com_baseinfo base"
                " LEFT JOIN PHA_COM_COMPANY comp on COMP.FAC_CODE = BASE.PRODUCER_CODE"
                " where BASE.valid_state = '1' "
                " and ( BASE.spell_code like '%%1%'"
                " or BASE.trade_name like '%%2%')";

    }
    else if(ui->rb_mat->isChecked())
    {
        sq = "select BASE.item_name 药品名称, BASE.specs 规格, BASE.item_code, "//0-2
                "BASE.pack_qty, BASE.kind_code,BASE.sale_price, "//3-5
                " BASE.pack_unit, '0' , "//6-7
                "'0','0','0',"//8-10 BASE.DOSE_MODEL_CODE,BASE.SELF_Flag,BASE.FEE_CODE,
                " '0','0',"//11-12 BASE.CLASS_CODE,BASE.BASE_DOSE,
                " COMP.company_NAME 生产厂家, '0' " //13-14
                " from mat_com_baseinfo base"
                " LEFT JOIN mat_COM_COMPANY comp on COMP.company_CODE = BASE.factory_CODE"
                " where BASE.valid_flag = '1' "
                " and ( BASE.spell_code like '%%1%'"
                " or BASE.item_name like '%%2%')";

    }
    else
    {
        QMessageBox::warning(this, "注意", "验收类别无效！");
        return ;
    }

    sq = sq.arg(key.toUpper()).arg(key);

    qDebug()<<"on_le returnPressed select sql : "<<sq<<"\n";

    md_search_pop->setQuery( sq , pub::db_o);

    if(md_search_pop->rowCount() == 0)
    {
        QMessageBox::information(this, "注意", "指定关键字找不到有效的项目！");
        return;
    }
    else if(md_search_pop->rowCount() == 1)
    {
        mpRecipeItemInfo["drug_name"] = md_search_pop->record(0).value(0).toString();
        mpRecipeItemInfo["specs"] = md_search_pop->record(0).value(1).toString();
        mpRecipeItemInfo["pack_qty"] = md_search_pop->record(0).value(3).toString();
        mpRecipeItemInfo["item_code"] = md_search_pop->record(0).value(2).toString();

        //if item is drug, current value is "drug_type", else is "exec_dept"
        mpRecipeItemInfo["exec_dept"] = md_search_pop->record(0).value(4).toString();

        mpRecipeItemInfo["pack_unit"] = md_search_pop->record(0).value(6).toString();
        mpRecipeItemInfo["price"] = md_search_pop->record(0).value(5).toString();
        mpRecipeItemInfo["drug_quality"] = md_search_pop->record(0).value(7).toString().trimmed();

        mpRecipeItemInfo["dose_model_code"] = md_search_pop->record(0).value(8).toString();
        mpRecipeItemInfo["self_made"] = md_search_pop->record(0).value(9).toString();
        mpRecipeItemInfo["fee_code"] = md_search_pop->record(0).value(10).toString();
        mpRecipeItemInfo["class_code"] = md_search_pop->record(0).value(11).toString();
        mpRecipeItemInfo["base_dose"] = md_search_pop->record(0).value(12).toString().trimmed();
        mpRecipeItemInfo["fac_name"] = md_search_pop->record(0).value(13).toString().trimmed();
        mpRecipeItemInfo["dose_unit"] = md_search_pop->record(0).value(14).toString().trimmed();


    }
    else
    {
        dlgGetItem->setDisplay(*md_search_pop,QRect(300, 150, 800, 500),"","0.3^0.2^0^0^0^0^0^0^0^0^0^0^0^0.3^0^0^0^0");

        dlgGetItem->setModal(true);
        dlgGetItem->exec();

        QString popRetStr = dlgGetItem->retStr();
        if(popRetStr.isEmpty())
        {
            return;
        }
        qDebug()<<"pop select return value is : "<<popRetStr;

        mpRecipeItemInfo["drug_name"] = pub::getStr(popRetStr, "^", 1);
        mpRecipeItemInfo["specs"] = pub::getStr(popRetStr, "^", 2);
        mpRecipeItemInfo["item_code"] = pub::getStr(popRetStr, "^", 3);
        mpRecipeItemInfo["pack_qty"] = pub::getStr(popRetStr, "^", 4);

        //if item is drug, current value is "drug_type", else is "exec_dept"
        mpRecipeItemInfo["exec_dept"] = pub::getStr(popRetStr, "^", 5);
        mpRecipeItemInfo["pack_unit"] = pub::getStr(popRetStr, "^", 7);
        mpRecipeItemInfo["price"] = pub::getStr(popRetStr, "^", 6);
        mpRecipeItemInfo["drug_quality"] = pub::getStr(popRetStr, "^", 8).trimmed();
        mpRecipeItemInfo["dose_model_code"] = pub::getStr(popRetStr, "^", 9).trimmed();
        mpRecipeItemInfo["self_made"] = pub::getStr(popRetStr, "^", 10).trimmed();
        mpRecipeItemInfo["fee_code"] = pub::getStr(popRetStr, "^", 11).trimmed();
        mpRecipeItemInfo["class_code"] = pub::getStr(popRetStr, "^", 12).trimmed();
        mpRecipeItemInfo["base_dose"] = pub::getStr(popRetStr, "^", 13).trimmed();
        mpRecipeItemInfo["dose_unit"] = pub::getStr(popRetStr, "^", 15).trimmed();

        mpRecipeItemInfo["fac_name"] = md_search_pop->record(0).value(14).toString();
    }

    QString info = mpRecipeItemInfo["drug_name"] + "^" +
            mpRecipeItemInfo["specs"] + "^"  +
            mpRecipeItemInfo["fac_name"];

    ui->le_item_info->setText(info);

}

void Yk_purchase_plan::on_le_key_browse_returnPressed()
{
    on_pb_search_2_clicked();
}

void Yk_purchase_plan::on_pb_check_search_clicked()
{
    QStringList sqlst = get_search_sql();
    if(sqlst.size() < 1)
    {
        return;
    }

    qDebug()<<"检索验收记录："<<sqlst<<"\n";

    md_check_list->setQuery(sqlst[0], pub::db_o);
    ui->tv_check_record->setModel(md_check_list);

    if(sqlst.size() > 1)
    {
        qro->exec(sqlst[1]);
        qro->next();

        ui->le_amount_2->setText(QString::number( qro->value(0).toDouble() , 'f' , 2));

        if(ui->le_amount_2->text() != "0.00" && //结果非 0
                ui->ckb_unpay_only->isChecked() && //未付款
                ui->ckb_supply_unit->isChecked() &&  //供应商唯一
                (ui->ckb_check_result->isChecked() &&  //校验结果为合格
                  ui->cbb_result->currentText() == "合格"))
        {
            ui->pb_set_pay_flag->setEnabled(true);
        }
        else
        {
            ui->pb_set_pay_flag->setEnabled(false);
        }
    }


}

QStringList Yk_purchase_plan::get_search_sql()
{

    QStringList sql_list;
    QString cond_company = "";
    QString cond_dept = "";
    QString cond_result = "";
    QString cond_date = "";
    QString cond_item = "";
    QString cond_pay = "";
    QString ret = "";
    int pos = -1;

    if(ui->ckb_unpay_only->isChecked())
    {
        cond_pay += " and pay_state = '0' ";
    }

    if(ui->ckb_check_result->isChecked())
    {
        if(ui->cbb_check_result->currentText() == "合格")
        {
            cond_result += " and check_result = '1' ";
        }
        else
        {
            cond_result += " and check_result = '0' ";
        }
    }

    if(ui->ckb_date_range->isChecked())
    {
        QDate dt1, dt2;
        dt1 = ui->de_begin->date();
        dt2 = ui->de_end->date();
        if(dt1 > dt2)
        {
            QMessageBox::information(this,"注意","指定的时间范围无效！");
            return sql_list;
        }

        cond_date = " and trunc(apply_date) >= to_date('" +
                dt1.toString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
        cond_date += " and trunc(apply_date) <= to_date('" +
                dt2.toString("yyyy-MM-dd") + "','yyyy-mm-dd') ";

    }

    if(ui->ckb_supply_unit->isChecked())
    {
        //入库来源
        if(ui->cbb_company_2->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定供货单位！" );
            return sql_list;
        }
        pos = pub::searchStr(company_code, "^", ui->cbb_company_2->currentText()) + 1;

        cond_company = " and company_code = '" + pub::getStr(company_code, "^", pos) + "' ";
    }
    else
    {
        cond_company = " and company_code like '%%'";
    }

    if(ui->ckb_store_unit->isChecked())
    {
        //检查当前工作库房
        if(ui->cbb_store_dept_2->currentText().isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定当前工作库房！" );
            return sql_list;
        }

        pos = pub::searchStr(store_depts, "^", ui->cbb_store_dept_2->currentText()) + 1;
        cond_dept = " and drug_dept_code = '" + pub::getStr(store_depts, "^", pos) + "' ";
    }

    if(ui->ckb_specified_item->isChecked())
    {
        if(mpRecipeItemInfo["item_code"].isEmpty())
        {
            QMessageBox::warning(this, "注意", "未指定药品信息！" );
            return sql_list;
        }
        else
        {
            cond_item = " and drug_code = '" + mpRecipeItemInfo["item_code"] + "'";
        }
    }

    //提取记录列表
    ret = "select cpny0.%1 供货公司, dpt.dept_name 入库库房, ck.apply_date 验收日期, ck.trade_name 项目名称,"//0-3
          " ck.specs 规格, ck.dose_model 剂型, ck.approve_no 批准文号,  cpny1.%1 生产厂家，"//4-7
          " ck.batch_no 批号, ck.manu_date 生产日期, ck.valid_date 有效期，"//8-10
          " ck.apply_num/ck.pack_qty 数量, ck.pack_unit 单位, ck.purchase_price 价格,"//11-13
          " case when ck.check_result = '1' then '合格' else '不合格' end 验收结论, ck.mark 备注, "//14-15
          " ck.input_check_no 验收序号"//16
          " from %2 ck"
          " left join %3 cpny0 on ck.company_code = cpny0.%4"
          " left join %3 cpny1 on ck.producer_code = cpny1.%4"
          " left join com_department dpt on ck.drug_dept_code = dpt.dept_code"
          " where 1 = 1 ";
    ret += cond_company + cond_date + cond_result + cond_dept + cond_item + cond_pay;
    ret += " and rownum < 999";

    if(ui->rb_company->isChecked())
    {
        ret += " order by ck.company_code, ck.apply_date";
    }
    else if(ui->rb_date->isChecked())
    {
        ret += " order by ck.apply_date, ck.company_code";
    }

    if(ui->rb_pha->isChecked())
    {
        ret = ret.arg("fac_name")
                .arg("pha_com_input_check")
                .arg("pha_com_company")
                .arg("fac_code");
    }
    else if(ui->rb_mat->isChecked())
    {
        ret = ret.arg("company_name")
                .arg("mat_com_input_check")
                .arg("mat_com_company")
                .arg("company_code");
    }
    else
    {
        return sql_list;
    }

    sql_list << ret;

    //汇总金额
    ret = " select sum(apply_num * purchase_price /pack_qty)  "//, company_code , producer_code
          " from %1 "
          " where 1 = 1 ";
    ret += cond_company + cond_date + cond_result + cond_dept + cond_item + cond_pay;
    //ret += " group by company_code , producer_code";

    if(ui->rb_pha->isChecked())
    {
        ret = ret.arg("pha_com_input_check");
    }
    else if(ui->rb_mat->isChecked())
    {
        ret = ret.arg("mat_com_input_check");
    }

    sql_list << ret;

    //设置结账标志
    ret = " update  %1 set pay_state = '2'"
          " where 1 = 1 ";
    ret += cond_company + cond_date + cond_result + cond_dept + cond_item + cond_pay;

    if(ui->rb_pha->isChecked())
    {
        ret = ret.arg("pha_com_input_check");
    }
    else if(ui->rb_mat->isChecked())
    {
        ret = ret.arg("mat_com_input_check");
    }

    sql_list << ret;

    return sql_list;
}


void Yk_purchase_plan::change_camera(QString cam_name)
{

    qDebug()<<"change camera \n";

    QSettings setIni("clin.ini", QSettings::IniFormat);

    int camera_mode = setIni.value("camera/"+cam_name+"/defaultMode").toInt();

    ui->imageList->setViewMode(QListView::IconMode);    //设置QListWidget的显示模式
    ui->imageList->setIconSize(QSize(200,150));//设置QListWidget中单元项的图片大小
    ui->imageList->setSpacing(10);//设置QListWidget中单元项的间距
    ui->imageList->setResizeMode(QListWidget::Adjust);//设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
    ui->imageList->setMovement(QListWidget::Static);//设置不能移动

    QString cam_device_name;

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        if(cameraList[i].description() == cam_name)
        {
            cam_device_name = cameraList[i].deviceName();
        }
    }


    if(cam_device_name.isEmpty())
    {
        QMessageBox::warning(this, "Note", "摄像头设备名称无效！");
    }

    camera=new QCamera(cam_device_name.toLatin1().data());//摄像头 .data()
    viewfinder=new QCameraViewfinder(this);//取景器
    ui->layout_capture->addWidget(viewfinder);
    camera->setViewfinder(viewfinder);
    camera->setCaptureMode(QCamera::CaptureStillImage);
    imageCapture=new QCameraImageCapture(camera);
    imageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);

    camera->start(); //启动摄像头

    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(cameraImageCaptured(int,QImage)));

    //获取摄像头支持的分辨率、帧率等参数
    QList<QCameraViewfinderSettings > ViewSets = camera->supportedViewfinderSettings();

    //设置摄像头参数
    if(ViewSets.count() >0)
    {
        if(ViewSets.count() > camera_mode)
        {
            QCameraViewfinderSettings vfs;
            double r ;
            vfs.setResolution(ViewSets[camera_mode].resolution());
            vfs.setPixelFormat(ViewSets[camera_mode].pixelFormat());
            r = ViewSets[camera_mode].maximumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMaximumFrameRate(r);
            }

            r = ViewSets[camera_mode].minimumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMinimumFrameRate(r);
            }

            vfs.setPixelAspectRatio(ViewSets[camera_mode].pixelAspectRatio());
            camera->setViewfinderSettings(vfs);
        }
        else
        {
            QMessageBox::information(this,"","摄像头参数无效，请重新设置！");
            camera->stop();
            camera->unload();

        }
    }
    else
    {
        QMessageBox::information(this,"","摄像头无可用启动参数 ！");
        camera->stop();
        camera->unload();

    }
}

void Yk_purchase_plan::camera_initial()
{

    qDebug()<<"will initial camera preview\n";

    dlgDelay->setText("正在初始化摄像头。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    //提取设备列表
    cameraList = QCameraInfo::availableCameras();

    if( 0 == cameraList.size())
    {
        qDebug()<<"has no camera.\n";
        QMessageBox::information(this, "注意" , "系统中找不到可用的摄像头！");
        has_camera = false;
        ui->cbb_cam_id->clear();

        dlgDelay->setNeedClose(true);
        dlgDelay->closeWindow();

        return;
    }
    else
    {
        has_camera = true;
    }

    QSettings setIni("clin.ini", QSettings::IniFormat);

    QString cur_cam_name = setIni.value("camera/defaultCamera").toString();
    int cur_cam_sn = setIni.value("camera/defaultId").toInt();
    int camera_mode = setIni.value("camera/"+cur_cam_name+"/defaultMode").toInt();

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        ui->cbb_cam_id->addItem(cameraList[i].description());
    }

    ui->cbb_cam_id->setCurrentText(cur_cam_name);

    if( ui->cbb_cam_id->currentText().isEmpty())
    {
        //默认摄像头不在列表中，启用列表中的第一个摄像头
        cur_cam_name = cameraList[0].description();
        camera_mode = setIni.value("camera/"+cur_cam_name+"/defaultMode").toInt();
    }

    ui->imageList->setViewMode(QListView::IconMode);    //设置QListWidget的显示模式
    ui->imageList->setIconSize(QSize(200,150));//设置QListWidget中单元项的图片大小
    ui->imageList->setSpacing(10);//设置QListWidget中单元项的间距
    ui->imageList->setResizeMode(QListWidget::Adjust);//设置自动适应布局调整（Adjust适应，Fixed不适应），默认不适应
    ui->imageList->setMovement(QListWidget::Static);//设置不能移动

    QString cam_device_name;

    cur_cam_name=ui->cbb_cam_id->currentText();

    for(int i = 0; i < cameraList.size(); i++)
    {
        //ui->cbb_cam_id->addItem(QString::number(i-1));
        if(cameraList[i].description() == cur_cam_name)
        {
            cam_device_name = cameraList[i].deviceName();
        }
    }


    if(cam_device_name.isEmpty())
    {
        QMessageBox::warning(this, "Note", "摄像头设备名称无效！");
    }

    if(camera == nullptr)
    {
        camera=new QCamera(cam_device_name.toLatin1().data());//摄像头 .data()
    }

    if(viewfinder == nullptr)
    {
        viewfinder=new QCameraViewfinder(this);//取景器
    }

    ui->layout_capture->addWidget(viewfinder);
    camera->setViewfinder(viewfinder);
    camera->setCaptureMode(QCamera::CaptureStillImage);
    if(imageCapture == nullptr)
    {
        imageCapture=new QCameraImageCapture(camera);
    }

    imageCapture->setCaptureDestination(QCameraImageCapture::CaptureToFile);
    qDebug()<<"imageCapture->setCaptureDestination finished.\n";

    camera->start(); //启动摄像头

    qDebug()<<"start camera. \n";

    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(cameraImageCaptured(int,QImage)));

    //获取摄像头支持的分辨率、帧率等参数
    QList<QCameraViewfinderSettings > ViewSets = camera->supportedViewfinderSettings();

    //设置摄像头参数
    bool finish = true;
    if(ViewSets.count() >0)
    {
        if(ViewSets.count() > camera_mode)
        {
            QCameraViewfinderSettings vfs;
            double r ;
            vfs.setResolution(ViewSets[camera_mode].resolution());
            vfs.setPixelFormat(ViewSets[camera_mode].pixelFormat());
            r = ViewSets[camera_mode].maximumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMaximumFrameRate(r);
            }

            r = ViewSets[camera_mode].minimumFrameRate();

            if(! qIsInf(r))
            {
                vfs.setMinimumFrameRate(r);
            }

            vfs.setPixelAspectRatio(ViewSets[camera_mode].pixelAspectRatio());
            camera->setViewfinderSettings(vfs);
        }
        else
        {
            QMessageBox::information(this,"","摄像头参数无效，请重新设置！");
            finish = false;
        }
    }
    else
    {
        QMessageBox::information(this,"","摄像头无可用启动参数 ！");
        finish = false;
    }

    if(!finish)
    {

        if(camera != nullptr)
        {
            camera->stop();
            camera->unload();
            delete camera;
            camera = nullptr;
        }

        if(viewfinder != nullptr)
        {
            delete viewfinder;
            viewfinder = nullptr;
        }

        if(imageCapture != nullptr)
        {
            delete imageCapture;
            imageCapture = nullptr;
        }

        camera_initialized = false;
        ui->pb_pic_save->setEnabled(false);
        ui->pb_cap_remove->setEnabled(false);
        ui->pb_cap_take->setEnabled(false);
        ui->pb_cap_setup->setEnabled(true);
    }
    else
    {
        camera_initialized = true;
        ui->pb_pic_save->setEnabled(true);
        ui->pb_cap_remove->setEnabled(true);
        ui->pb_cap_take->setEnabled(true);
        ui->pb_cap_setup->setEnabled(true);
    }

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

}

void Yk_purchase_plan::cameraImageCaptured(int, QImage image)
{
    qDebug()<<"cameraImageCaptured\n";
    //search valid filename
    QString fileName ,fName;
    while(true)
    {
        pic_num ++;
        fileName = pic_path + "/" + QString::number(pic_num)+".jpg";

        if (!QFile::exists(fileName))
        {
            break;
        }
    }

    image.save(fileName);
    QString desc = ui->cbb_pic_type->currentText();

    desc += "^" + QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz") +
            "^" + ui->le_pic_describe->text().trimmed();

    qDebug()<<"图片描述："<<desc<<"\n";

    pic_describe[QString::number(pic_num)] = desc;

    //定义QListWidgetItem对象
    QListWidgetItem *imageItem = new QListWidgetItem;
    //为单元项设置属性
    imageItem->setIcon(QIcon(fileName));
    QFont ft = QFont();
    ft.setPointSize(10);
    imageItem->setFont(ft);
    imageItem->setText(fileName);
    //重新设置单元项图片的宽度和高度
    imageItem->setSizeHint(QSize(200,150));
    //将单元项添加到QListWidget中
    ui->imageList->addItem(imageItem);

    //ui->pbDelete->setEnabled(true);

}

void Yk_purchase_plan::on_pb_cap_take_clicked()
{
//    if(mpPatientInfo["clinic_code"].isEmpty())
//    {
//        QMessageBox::information(this, "注意", "患者信息无效！");
//        return ;
//    }
    imageCapture->capture();
}

void Yk_purchase_plan::on_pb_cap_setup_clicked()
{
    qDebug()<<"enter cap setup.\n";

    dlgDelay->setText("正在初始化摄像头。。。");
    dlgDelay->setModal(true);
    dlgDelay->setNeedClose(false);
    dlgDelay->show();
    qApp->processEvents();

    if(camera != nullptr)
    {
        qDebug()<<"camera is not null, clear camera info.\n";
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(cap_setup == nullptr)
    {
        qDebug()<<"cap_setup is null, create new instance.\n";
        cap_setup = new Ys_cap_setup();//摄像头设置
    }

    dlgDelay->setNeedClose(true);
    dlgDelay->closeWindow();

    qDebug()<<"cap_setup created.\n";
    cap_setup->exec();

    qDebug()<<"cap_setup exec finish.\n";
    //change_camera(ui->cbb_cam_id->currentText());
    camera_initial();

}

void Yk_purchase_plan::on_cbb_cam_id_currentTextChanged(const QString &arg1)
{
    if(!camera_initialized)
    {
        return;
    }
    qDebug()<<"camera changed.\n";

    if(camera != nullptr)
    {
        camera->stop();
        camera->unload();
        delete camera;
        camera = nullptr;
    }

    if(viewfinder != nullptr)
    {
        delete viewfinder;
        viewfinder = nullptr;
    }

    if(imageCapture != nullptr)
    {
        delete imageCapture;
        imageCapture = nullptr;
    }

    change_camera(arg1);
}

void Yk_purchase_plan::on_pb_cap_remove_clicked()
{
    if( -1 == ui->imageList->currentRow() )
    {
        QMessageBox::about(this,"提示","请先选中要删除的图片！");
        return;
    }

    QString tmpFile = ui->imageList->currentItem()->text();

    QDir *destFile = new QDir;
    bool exist = destFile->exists(tmpFile);

    if (exist)
    {
        destFile->remove(tmpFile);
        delete ui->imageList->currentItem();
    }

    if( -1 == ui->imageList->currentRow() )
    {
    //    ui->pbDelete->setEnabled(false);
    }

}

void Yk_purchase_plan::on_pb_pic_save_clicked()
{

    qDebug()<<"on_pb_pic_save_clicked()\n";

    QDir d = QDir(pic_path);
    d.setNameFilters( QStringList("*.jpg") );
    QStringList files = d.entryList();  //read filenames

    if(files.size() < 1)
    {
        qDebug()<<"no image file found.\n";
        QMessageBox::warning(this, "Note", "无有效图像文件！");
        ui->imageList->clear();
        return;
    }

    if(ui->lw_selected->count() < 1)
    {
        QMessageBox::warning(this, "Note", "未指定图像关联信息！");
        ui->imageList->clear();
        return;
    }

    //
    QString dt_str = QDate::currentDate().toString("yyyy-MM-dd");
    QString dest_path = pic_path+"/" + dt_str;
    QDir dest_d = QDir();

    if(!dest_d.exists(dest_path))
    {
        dest_d.mkdir(dest_path);
    }

    QList<QListWidgetItem *> selected_items = ui->lw_selected->findItems("", Qt::MatchContains);
    QString pic_sq, dest_filename;
    QStringList sqls;
    QStringList check_nos;
    QString check_type;//类别，药品或物资

    if(ui->rb_pha->isChecked())
    {
        check_type = "pha";
    }
    else if(ui->rb_mat->isChecked())
    {
        check_type = "mat";
    }
    else
    {
        qDebug()<<"未选择校验类型！\n";
        return;
    }

    foreach( QListWidgetItem * itm, selected_items)
    {
        QString item_str = itm->text();

        QString check_no = pub::getStr(item_str, "^", 1);

        for(int i = 0; i < files.size() ; i++)
        {
            QFile f(pic_path + "/" + files[i]);

            QFileInfo f_inf(f);
            QString baseName = f_inf.baseName();    //为提取图像文件描述
            QString pic_desc = pic_describe[baseName];

            dest_filename = pub::getStr(pic_desc, "^", 2) + ".jpg"; //check_no + "-" +

            QString sync_flag = "0";

            if(!f.exists(dest_path + "/" + dest_filename))
            {
                //同一图像文件可能被多个项目关联，复制一次即可
                if(!f.copy(dest_path + "/" + dest_filename))
                {
                    QMessageBox::warning(this, "Note", "本地图像文件转储失败！");
                    return;
                }

                if(remote_file_syncronize(dest_path, dest_filename))
                {
                    sync_flag = "1";
                }
            }

            pic_sq = "('" + pub::usr_name + "'," +
                    "'" + pub::usr_code + "', " +
                    "now() ," +
                    "'" + pub::getStr(pic_desc, "^", 1) + "'," +
                    "'" + pub::getStr(pic_desc, "^", 3) + "'," +
                    "'" + dt_str + "'," +
                    "'" + dest_filename + "'," +
                    "'" + check_no + "'," +
                    "'" + pub::getStr(item_str, "^", 2) + "'," +
                    "'" + pub::getStr(item_str, "^", 3) + "'," +
                    "'" + check_type + "', "//tm_mark,类别标志
                    "'" + sync_flag + "')";
            sqls <<pic_sq;

            if(check_nos.indexOf(check_no) < 0)
            {
                check_nos << check_no;
            }
        }
    }

    pic_sq = "insert into yk_drug_check_pic "
             "(oper_name, oper_code, oper_date, "
             " pic_type, pic_describe, pic_dir, pic_name, "
             " drug_check_no, drug_name, drug_code, "
             " tm_mark, sync_flag) "
             " values " + sqls.join(",");

    qDebug()<<"保存图像信息："<<pic_sq<<"\n";

    if(!qrm->exec(pic_sq))
    {
        QMessageBox::warning(this, "Note", "图像信息保存失败！");
        return;
    }

    sq = "update %1 set has_pic = '1' "
         " where input_check_no in ('" + check_nos.join("','") + "')";
    if(ui->rb_pha->isChecked())
    {
        sq = sq.arg("pha_com_input_check");
    }
    else if(ui->rb_mat->isChecked())
    {
        sq = sq.arg("mat_com_input_check");
    }

    qDebug()<<"设置验收记录图像关联标志："<<sq<<"\n";
    qro->exec(sq);

    QMessageBox::warning(this, "Note", "图像信息已保存！");

    qDebug()<<"移除临时图像文件。\n";
    for(int i = 0; i < files.size() ; i++)
    {
        QFile f(pic_path + "/" + files[i]);
        f.remove();
    }

    ui->imageList->clear();

    ui->lw_selected->clear();
}

bool Yk_purchase_plan::remote_file_syncronize(QString file_path, QString file_name)
{
    qDebug()<<"remote_file_syncronize\n";

    //提取最后一层目录名称
    QStringList tmp = file_path.split("/");
    QString deepest_path = tmp[tmp.size()-1];

    QDir dest_d = QDir();
    QFile fl;

    QString dest_path = remote_path + "/" + deepest_path;

    if(!dest_d.exists(dest_path))
    {
        dest_d.mkdir(dest_path);
    }

    QString remote_name = dest_path + "/" + file_name;

    QString sour = file_path + "/" + file_name;
    QString dest = dest_path + "/" + file_name;
    qDebug()<<"deepest_path : "<<deepest_path<<"\n";
    qDebug()<<"source : "<<sour<<"\n";
    qDebug()<<"destination : "<<dest<<"\n";
    if(fl.copy(sour, dest))
    {
        return true;
    }
    else
    {
        return false;
    }

}

void Yk_purchase_plan::on_pb_pic_refresh_clicked()
{

}

void Yk_purchase_plan::on_tv_pic_display_doubleClicked(const QModelIndex &index)
{
    on_tv_pic_display_clicked(index);
}

void Yk_purchase_plan::on_tv_pic_display_clicked(const QModelIndex &index)
{
    qDebug()<<"on_tv_pic_display_clicked\n";

    QString pic_type = index.siblingAtColumn(1).data().toString();
    QString pic_desc = index.siblingAtColumn(2).data().toString();
    QString sync_flag = index.siblingAtColumn(3).data().toString();
    QString pic_dir = index.siblingAtColumn(4).data().toString();
    QString pic_name = index.siblingAtColumn(5).data().toString();
    QString oper_code = index.siblingAtColumn(7).data().toString();

    ui->le_pic_describe_2->setText(pic_desc);
    ui->cbb_pic_type_2->setCurrentText(pic_type);

    QString local_flnm = pic_path + "/" + pic_dir + "/" + pic_name;
    QString remote_flnm = remote_path + "/" + pic_dir + "/" + pic_name;

    qDebug()<<"local, remote : "<<local_flnm<<","<< remote_flnm;

    bool local_exist = QFile::exists(local_flnm);
    bool remote_exist = QFile::exists(remote_flnm);

    if(!local_exist && !remote_exist)
    {
        qDebug()<<"本地远程均无文件\n";
        QMessageBox::information(this, "注意", "本地和远程均找不到文件！");
        return;
    }

    if(local_exist && !remote_exist)
    {
        qDebug()<<"本地有，远程无，由本地向同步远程\n";
        QDir dest_d = QDir();
        QString dest_path = remote_path + "/" + pic_dir;

        if(!dest_d.exists(dest_path))
        {
            dest_d.mkdir(dest_path);
        }

        if(!QFile::copy(local_flnm, remote_flnm))
        {
            qDebug()<<"文件复制失败\n";
        }
    }

    if(!local_exist && remote_exist)
    {
        qDebug()<<"本地无，远程有，由远程向同步本地\n";
        QDir dest_d = QDir();
        QString dest_path = pic_path + "/" + pic_dir;

        if(!dest_d.exists(dest_path))
        {
            dest_d.mkdir(dest_path);
        }

        if(!QFile::copy(remote_flnm, local_flnm))
        {
            qDebug()<<"文件复制失败\n";
        }
    }

    //显示本地图像
    local_exist = QFile::exists(local_flnm);

    if(!local_exist)
    {
        qDebug()<<"本地文件无效\n";
        QMessageBox::information(this, "注意", "本地文件无效！");
        return;
    }

    qDebug()<<"file name is : "<<local_flnm<<"\n";

    //QImage image(flnm);

    QPixmap pixmap(local_flnm);

    scene->clear();
    pixmapItem = scene->addPixmap(pixmap);
    view->setAlignment(Qt::AlignCenter); // 设置内容居中
    pic_scale_factor = 1;
    scene->setSceneRect(pixmap.rect()); // 设置场景矩形为图像大小
    pic_fitToView();// 自动缩放到合适大小

    if(pub::usr_code == oper_code)
    {
        ui->pb_pic_describe_change->setEnabled(true);
    }
    else
    {
        ui->pb_pic_describe_change->setEnabled(false);
    }

}

void Yk_purchase_plan::pic_fitToView()
{
    if (!pixmapItem) return;

    // 获取视图和图像尺寸
    QSize viewSize = view->size();
    QSize imageSize = pixmapItem->pixmap().size();

    // 计算合适的缩放比例
    double widthRatio = static_cast<double>(viewSize.width()) / imageSize.width();
    double heightRatio = static_cast<double>(viewSize.height()) / imageSize.height();
    double fitFactor = qMin(widthRatio, heightRatio);

    // 应用缩放
    pic_scale_factor = fitFactor;
    view->resetTransform();
    view->scale(pic_scale_factor, pic_scale_factor);
}

void Yk_purchase_plan::pic_zoomIn()
{
    pic_scale_factor *= 0.8;
    view->setTransform(QTransform::fromScale(pic_scale_factor, pic_scale_factor));
}

void Yk_purchase_plan::pic_zoomOut()
{
    pic_scale_factor *= 1.2;
    view->setTransform(QTransform::fromScale(pic_scale_factor, pic_scale_factor));
}

void Yk_purchase_plan::on_pb_pic_upload_clicked()
{

}

void Yk_purchase_plan::on_pb_pic_describe_change_clicked()
{

    qDebug()<<"on_pb_pic_describe_change_clicked\n";

    if(!ui->tv_pic_display->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未选定有效图像信息！");
        return;
    }

    QString atinc = ui->tv_pic_display->currentIndex().siblingAtColumn(6).data().toString();
    QString pic_type = ui->cbb_pic_type_2->currentText();

    sq = "update yk_drug_check_pic set pic_describe = '%1', pic_type = '%2'"
         " where atinc = %3 ";

    sq = sq.arg(ui->le_pic_describe_2->text().trimmed())
            .arg(pic_type)
            .arg(atinc);
    qDebug()<<"change pic_describe. \n";

    qrm->exec(sq);

    QMessageBox::information(this, "注意", "信息已变更，再次进入可以看到变更结果。");

    on_pb_pic_refresh_clicked();
}

void Yk_purchase_plan::on_pb_camera_initial_clicked()
{

    if(camera_initialized)
    {
        QMessageBox::information(this, "注意", "摄像头设备已经启动！");
    }
    else
    {
        camera_initial();
    }


//    if(cap_setup == nullptr)
//    {
//        cap_setup = new Ys_cap_setup();
//    }
}

void Yk_purchase_plan::on_pb_get_pic_clicked()
{
    if(!ui->tv_check_record->currentIndex().isValid())
    {
        QMessageBox::information(this, "注意", "未指定需要查询的验收记录！");
        return;
    }

    ui->tabWidget->setCurrentIndex(3);

    qDebug()<<"on_pb_get_pic_clicked\n";

    sq = "select oper_date 日期, "//0
         " pic_type 类型, "//1
         " pic_describe 内容 , " //2
         " sync_flag , pic_dir , pic_name, atinc, oper_code" //3-7
         " from yk_drug_check_pic "
         " where drug_check_no = '%1'"
         " order by atinc";
    sq = sq.arg(ui->tv_check_record->currentIndex().siblingAtColumn(16).data().toString());

    qDebug()<<"display image describe:\n"<<sq;

    md_pics->setQuery(sq, pub::db_m);
    ui->tv_pic_display->setModel(md_pics);
    int w = ui->tv_pic_display->width();
    pub::setColumnWidth(ui->tv_pic_display, "0^0.4^0.4^0^0^0^0^0^0", w);

    ui->pb_pic_describe_change->setEnabled(false);
}

void Yk_purchase_plan::on_pb_fresh_check_record_clicked()
{
    QString cond = "";
    if(ui->ckb_date_range_2->isChecked())
    {
        QDate dt1, dt2;
        dt1 = ui->de_begin->date();
        dt2 = ui->de_end->date();
        if(dt1 > dt2)
        {
            QMessageBox::information(this,"注意","指定的时间范围无效！");
            return ;
        }

        cond += " and trunc(apply_date) >= to_date('" +
                dt1.toString("yyyy-MM-dd") + "','yyyy-mm-dd') ";
        cond += " and trunc(apply_date) <= to_date('" +
                dt2.toString("yyyy-MM-dd") + "','yyyy-mm-dd') ";

    }

    if(ui->ckb_only_no_pic->isChecked())
    {
        cond += " and has_pic = '0' ";
    }

    sq = "select cpny.%2 供货公司, trunc(ck.apply_date) 验收日期, ck.trade_name 药品名称, ck.specs 规格,"
         " ck.batch_no 批号, ck.apply_num/ck.pack_qty 数量, ck.pack_unit 单位, ck.input_check_no 序号"
         " from %3 ck  "
         " left join %4 cpny on ck.company_code = cpny.%5 "
         " where 1 = 1 %1 order by ck.company_code, ck.apply_date";
    sq = sq.arg(cond);
    if(ui->rb_pha->isChecked())
    {
        sq = sq.arg("fac_name")
                .arg("pha_com_input_check")
                .arg("pha_com_company")
                .arg("fac_code");
    }
    else if(ui->rb_mat->isChecked())
    {
        sq = sq.arg("company_name")
                .arg("mat_com_input_check")
                .arg("mat_com_company")
                .arg("company_code");
    }
    else
    {
        return;
    }
    qDebug()<<"提取需要采集图像的记录："<<sq<<"\n";
    md_check_to_take_pic->setQuery(sq, pub::db_o);
    ui->tv_check_list->setModel(md_check_to_take_pic);
    //int w = ui->tv_check_list->width();

}

void Yk_purchase_plan::on_tv_check_list_doubleClicked(const QModelIndex &index)
{
    QString str = index.siblingAtColumn(7).data().toString() + "^" +
            index.siblingAtColumn(2).data().toString() + "^" +
            index.siblingAtColumn(3).data().toString() + "^" +
            index.siblingAtColumn(5).data().toString() + "^" +
            index.siblingAtColumn(6).data().toString() ;

    QList<QListWidgetItem *> lst = ui->lw_selected->findItems(str, Qt::MatchExactly);

    if(lst.size() > 0)
    {
        return;
    }

    if(ui->lw_selected->count() == 0)
    {
        //如新是第一行，保存供货公司名称
        current_pic_company = index.siblingAtColumn(0).data().toString();
    }
    else
    {
        //非第一行，检查新加入的供货公司名称是否与先前一致
        if(current_pic_company != index.siblingAtColumn(0).data().toString())
        {
            QMessageBox::information(this,"注意","一次图像采集只允许关联同一供货公司！");
            return ;
        }
    }

    ui->lw_selected->addItem(str);

    has_edited = true;

}

void Yk_purchase_plan::on_lw_selected_doubleClicked(const QModelIndex &index)
{
     ui->lw_selected->takeItem(ui->lw_selected->currentRow());

     if(ui->lw_selected->count() < 1)
     {
         has_edited = false;
     }
}

void Yk_purchase_plan::on_rb_pha_clicked()
{
    set_store_type();
}

void Yk_purchase_plan::on_rb_mat_clicked()
{
    set_store_type();
}

void Yk_purchase_plan::on_pb_set_pay_flag_clicked()
{
    QStringList sqlist = get_search_sql();
    if(sqlist.size() > 2)
    {
        if(qro->exec(sqlist[2]))
        {
            QMessageBox::information(this,"注意","付款标志已经保存！");
        }
        else
        {
            QMessageBox::information(this,"注意","付款标志保存失败！");
        }
    }
}
